<?php

namespace App\Service\admin;

use App\Models\product\ProductCommissionRuleModel;
use App\Models\product\ProductModel;
use App\Models\product\ProductSonModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;
use lxs\tools\Tools;

class ProductService extends BaseStatic
{

    /**
     * 获取产品提成比例
     * @param mixed $value
     * @param int $class_id
     * @param int $belong_id
     * @return mixed
     */
    public function getProductCommissionRatio(mixed $value, int $belong_id, int $class_id): mixed
    {
        if ($value == 0) {
            $value = ProductCommissionRuleModel::where('belong_id', $belong_id)
                ->where('class_id', $class_id)
                ->where('deleted_at', 0)
                ->value('commission_rate');
        }
        return $value;
    }


    /**
     * 添加产品生成权重
     */
    public function productCreateWeight($num): bool
    {
        if ($num > 0) {
            try {
                $sortData = ProductModel::where('deleted_at', 0)
                    ->where('sort', 999)
                    ->orderBy('update_at', 'desc')
                    ->get();
                if ($sortData) {
                    foreach ($sortData as $k => $v) {
                        $v->sort_pid = $k + 1;
                        $v->save();
                    }
                }
                return true;
            } catch (\Exception $e) {
                Log::error(date('Y-m-d H:i:s') . '添加产品生成权重失败：' . $e->getMessage());
                return false;
            }
        }
        return true;
    }


    /**
     * 编辑产品
     */
    public function productFromSubmit($data): array
    {
        $platformData = json_decode($data['platformData'], true);
        if (!$platformData) {
            return self::serviceReturn(3001, '平台数据不能为空');
        }

        try {
            DB::beginTransaction();

            if (isset($data['id'])) {

                $product_title = ProductModel::where('deleted_at', 0)
                    ->where('online_platform', $data['online_platform'])
                    ->where('product_title', $data['product_title'])
                    ->where('id', '!=', $data['id'])
                    ->value('product_title');
                if ($product_title) {
                    return self::serviceReturn(3001, '产品标题已存在');
                }

                if (isset($data['delete_ids'])) {
                    ProductSonModel::whereIn('id', $data['delete_ids'])->update(['deleted_at' => time()]);
                }

            } else {

                $product_title = ProductModel::where('online_platform', $data['online_platform'])->where('product_title', $data['product_title'])->value('product_title');
                if ($product_title) {
                    return self::serviceReturn(3001, '产品标题已存在');
                }

            }

            $i = 0;
            $popularize_platform_data = [];
            foreach ($platformData as $v) {

                if (empty($data['id'])) {
                    $productInfo = new ProductModel();
                    $productInfo->product_type = $data['product_type'];
                    $productInfo->class_id = $data['class_id'];
                    $productInfo->online_platform = $data['online_platform'];
                    $productInfo->create_time = time();
                    $i++;
                } else {
                    $productInfo = ProductModel::find($data['id']);
                    $productInfo->product_type = ProductModel::getProductType($data['product_type']);
                }
                $productInfo->belong_id = $data['belong_id'];
                $popularize_platform_data[] = $v['popularize_platform'];
                $popularize_platform_str = implode(',', $popularize_platform_data);
                $productInfo->popularize_platform = $popularize_platform_str;
                $productInfo->live_time = Tools::timeConvert($data['live_time']);
                $productInfo->product_title = $data['product_title'];
                $productInfo->product_cover = $data['product_cover'];
                $productInfo->product_intro = $data['product_intro'];
                $productInfo->commission_ratio = $this->getProductCommissionRatio($data['commission_ratio'], $productInfo->belong_id, $productInfo->class_id);
                $productInfo->save();


                $productSon = empty($v['id']) ? new ProductSonModel() : ProductSonModel::find($v['id']);
                $productSon->product_id = $productInfo->id;
                $productSon->popularize_id = $v['popularize_platform'];
                $productSon->platform_link = $v['platform_link'];
                $productSon->share_link = '';
                $productSon->appid = $v['appid'] ?? '';
                $productSon->secret = $v['secret'] ?? '';
                $productSon->path = $v['path'] ?? '';
                $productSon->save();

            }

            $this->productCreateWeight($i);

            DB::commit();
            return self::serviceReturn(200, '提交成功');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(date('Y-m-d H:i:s') . '编辑产品失败：' . $e->getMessage() . $e->getLine() . $e->getFile());
            return self::serviceReturn(3001, '编辑产品失败');
        }

    }


}
